package com.yiqi.liebang.feature.login.view;

import android.content.Intent;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.flyco.tablayout.SegmentTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.google.gson.Gson;
import com.suozhang.framework.component.http.Host;
import com.suozhang.framework.entity.bo.UserInfoBo;
import com.suozhang.framework.framework.AM;
import com.suozhang.framework.framework.BaseActivity;
import com.suozhang.framework.utils.HttpRootSelectUtils;
import com.suozhang.framework.utils.T;
import com.suozhang.framework.widget.PowerfulEditText;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareConfig;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.yiqi.liebang.R;
import com.yiqi.liebang.common.rongim.SealAppContext;
import com.yiqi.liebang.entity.bo.RegisterBo;
import com.yiqi.liebang.entity.bo.WxUserBo;
import com.yiqi.liebang.feature.login.contract.LoginContract;
import com.yiqi.liebang.feature.login.dependencies.login.DaggerLoginComponent;
import com.yiqi.liebang.feature.login.dependencies.login.LoginPresenterModule;
import com.yiqi.liebang.feature.setting.view.BindPhoneActivity;
import com.yiqi.liebang.feature.setting.view.ServiceAgreementActivity;
import com.yiqi.liebang.framework.api.ApiLib;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnLongClick;
import cn.jpush.android.api.JPushInterface;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.rong.imkit.RongIM;

public class LoginActivity extends BaseActivity implements LoginContract.View{
    @Inject
    LoginContract.Presenter mPresenter;

    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.tl_1)
    SegmentTabLayout mTab;
    @BindView(R.id.view_user_register)
    LinearLayout mViewUserRegister;
    @BindView(R.id.view_user_login)
    LinearLayout mViewUserLogin;
    @BindView(R.id.edt_user_register_mobile)
    PowerfulEditText mEdtUserRegisterMobile;
    @BindView(R.id.btn_user_send_code)
    TextView mBtnUserSendCode;
    @BindView(R.id.edt_user_register_code)
    PowerfulEditText mEdtUserRegisterCode;
    @BindView(R.id.edt_user_register_pwd)
    PowerfulEditText mEdtUserRegisterPwd;
    @BindView(R.id.edt_user_register_nick)
    PowerfulEditText mEdtUserRegisterNick;
    @BindView(R.id.edt_user_login_mobile)
    PowerfulEditText mEdtUserLoginMobile;
    @BindView(R.id.edt_user_login_pwd)
    PowerfulEditText mEdtUserLoginPwd;
    @BindView(R.id.cbx_lottery_daleto)
    CheckBox mCbxService;
    @BindView(R.id.btn_user_register)
    TextView mBtnUserRegister;
    private String[] mTitles = {"注册", "登录"};
    private UMShareAPI mShareAPI;

    private UserInfoBo mUserData;
    WxUserBo mWxUserInfoBo;

    private Integer mBindingTypetype;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_login;
    }

    @Override
    protected void initInjector() {
        DaggerLoginComponent.builder().loginPresenterModule(new LoginPresenterModule(this)).build().inject(this);
    }

    @Override
    protected void initView() {
        mTab.setTabData(mTitles);
        mTab.setCurrentTab(0);
        initToolBar(mToolbar, "注册", true, true);
    }

    @Override
    protected void initData() {
        UMShareConfig config = new UMShareConfig();
        config.isNeedAuthOnGetUserInfo(true);
        mShareAPI = UMShareAPI.get(this);
        mShareAPI.setShareConfig(config);
    }

    @Override
    protected void initEvent() {
        mTab.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                initShow(position);
            }

            @Override
            public void onTabReselect(int position) {
            }
        });

        mCbxService.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    mBtnUserRegister.setBackgroundResource(R.drawable.bg_user_login_btn);
                    mBtnUserRegister.setEnabled(true);
                    mBtnUserRegister.setClickable(true);
                } else {
                    mBtnUserRegister.setEnabled(false);
                    mBtnUserRegister.setClickable(false);
                    mBtnUserRegister.setBackgroundResource(R.drawable.bg_user_login_enable);
                }
            }
        });
    }

    private void initShow(int type) {

        if (type == 0) {
            mViewUserRegister.setVisibility(View.VISIBLE);
            mViewUserLogin.setVisibility(View.GONE);
            initToolBar(mToolbar, "注册", true, true);

        } else {
            mViewUserRegister.setVisibility(View.GONE);
            mViewUserLogin.setVisibility(View.VISIBLE);
            initToolBar(mToolbar, "登录", true, true);
        }

    }


    @OnClick({R.id.btn_user_send_code, R.id.btn_user_register, R.id.btn_to_xieyi, R.id.btn_user_forget_pwd, R.id.btn_user_login, R.id.btn_user_login_wx, R.id.btn_user_login_wb})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_user_send_code:
                mPresenter.sendCode(
                        mEdtUserRegisterMobile.getText().toString());
                break;
            case R.id.btn_user_register:
                mPresenter.userRegister(
                        mEdtUserRegisterMobile.getText().toString(),
                        mEdtUserRegisterCode.getText().toString(),
                        mEdtUserRegisterPwd.getText().toString(),
                        mEdtUserRegisterNick.getText().toString(),
                        JPushInterface.getRegistrationID(this));

                break;
            case R.id.btn_user_forget_pwd:
                startActivity(new Intent(this, ResetPwdActivity.class));
                break;
            case R.id.btn_user_login:
                mPresenter.userLogin(mEdtUserLoginMobile.getText().toString(),
                        mEdtUserLoginPwd.getText().toString(), JPushInterface.getRegistrationID(this));
                break;
            case R.id.btn_user_login_wx:
                mBindingTypetype=1;
                initUmLoginWx(SHARE_MEDIA.WEIXIN);
                break;
            case R.id.btn_user_login_wb:
                mBindingTypetype=2;
                break;
            case R.id.btn_to_xieyi:
                startActivity(new Intent(this, ServiceAgreementActivity.class));
                break;
        }
    }

    private void initUmLoginWx(final SHARE_MEDIA type) {
        try {
            if (!mShareAPI.isInstall(this, SHARE_MEDIA.WEIXIN)) {
                T.showShort("您未安装微信！");
                return;
            }
        } catch (Exception e) {
            showMsg(e.getMessage());
        }

        mShareAPI.getPlatformInfo(LoginActivity.this, type, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {

            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                if (map == null) return;
                Gson gson = new Gson();
                String s = gson.toJson(map);
                mWxUserInfoBo = gson.fromJson(s, WxUserBo.class);
                if (mWxUserInfoBo != null) {
                    mPresenter.thirdLogin(
                            mWxUserInfoBo.getOpenid(),
                            mWxUserInfoBo.getName(),
                            JPushInterface.getRegistrationID(LoginActivity.this),
                            mWxUserInfoBo.getProfile_image_url(), 0);
                }

            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                T.showShort(throwable.getMessage());
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {

            }
        });
    }

    @Override
    public void showReisterSuccess() {
        showMsg("注册成功！");
        finish();
    }


    @Override
    public void showError(String error) {
        showMsg(error);
    }

    @Override
    public void showLoginSuccess() {
//        showMsg("登录成功！");
        finish();
    }

    @Override
    public void showThirdLoginSuccess(UserInfoBo userInfoBo) {
        mUserData = userInfoBo;
        thirdLoginSuccess(mUserData);
    }

    private void thirdLoginSuccess(UserInfoBo value) {
        if (value.getIsPhone() == 0) {
            Intent intent = new Intent(this, BindPhoneActivity.class);
            if (mWxUserInfoBo != null) {
                {
                    intent.putExtra("openid", mWxUserInfoBo.getOpenid());
                    intent.putExtra("type", mBindingTypetype);
                    startActivityForResult(intent, 1);
                }
            }
        } else {
            T.showShort("登录成功!");
            AM.user().saveLoginResultCache(value == null ? null : value);
            if (!TextUtils.isEmpty(value.getRongCloudToken())) {
                RongIM.connect(value.getRongCloudToken(), SealAppContext.getInstance().getConnectCallback());
            } else {
                T.showShort("融云连接失败!");
            }
            finish();

        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null && resultCode == 2) {
            int res = data.getIntExtra("is_ok", 0);
            if (res == 999) {
                AM.user().saveLoginResultCache(mUserData == null ? null : mUserData);
                if (!TextUtils.isEmpty(mUserData.getRongCloudToken())) {
                    RongIM.connect(mUserData.getRongCloudToken(), SealAppContext.getInstance().getConnectCallback());
                } else {
                    T.showShort("融云连接失败!");
                }
                finish();
            }
        }
    }

    @Override
    public void showResetSuccess(UserInfoBo s) {

    }


    @Override
    public void showCodeSuccess(RegisterBo s) {
        T.showShort("获取验证码成功!");
        mEdtUserRegisterCode.setText(s.getCode());
        onGetCode();
    }


    public void onGetCode() {
        final int count = 60;//倒计时10秒
        Observable.interval(0, 1, TimeUnit.SECONDS)
                .take(count + 1)
                .map(new Function<Long, Long>() {
                    @Override
                    public Long apply(Long aLong) throws Exception {
                        return count - aLong;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())//ui线程中进行控件更新
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        mBtnUserSendCode.setEnabled(false);
                        mBtnUserSendCode.setTextColor(AM.res().getColor(R.color.primary_highlight));
                    }
                }).subscribe(new Observer<Long>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Long num) {

                mBtnUserSendCode.setText(num + "s");
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {
                //回复原来初始状态
                mBtnUserSendCode.setEnabled(true);
                mBtnUserSendCode.setText("发送验证码");
                mBtnUserSendCode.setTextColor(AM.res().getColor(R.color.text_primary));
            }
        });

    }




    private int count = 0;
    private boolean isOk = false;

    @OnClick(R.id.btn_choose)
    public void onVersionClicked() {
        if (!AM.isDebug()) {
            return;
        }
        count++;
        //连续点击5次 弹出选择框
        if (count >= 5) {
            isOk = true;
            showMsg("Test mode enabled!");
        }
    }

    @OnLongClick(R.id.btn_choose)
    public boolean onVersionLongClicked() {
        if (isOk) {
            count = 0;
            isOk = false;
            showHostSelector();
        }
        return true;
    }

    private void showHostSelector() {
        HttpRootSelectUtils.selectHttpRoot(this, new HttpRootSelectUtils.ResetHostListener() {
                    @Override
                    public void onResetHost(Host host) {
                        resetHost(host);
                        showMsg("切换成功");
                    }
                },
                null);
    }
    /**
     * 重新设置主机头
     *
     * @param host
     */
    private void resetHost(Host host) {
        ApiLib.resetHost(host);
        initInjector();
    }
}
